<?php
/**
 * @version $Id: functions.php 24 2010-05-21 14:47:16Z vladzimirs $
 * @package UnoCart
 * @copyright Авторские права (C) 2009-2010 UnoCart team & (C) 2007-2010 Joostina team &. Все права защищены.
 * @license Лицензия http://www.gnu.org/licenses/gpl-2.0.htm GNU/GPL, или help/license.php
 * UnoCart! - свободное программное обеспечение распространяемое по условиям лицензии GNU/GPL
 * Для получения информации о используемых расширениях и замечаний об авторском праве, смотрите файл help/copyright.php.
 */
defined('_VALID_MOS') or die('Restricted access');
function trace($param, $die = 0)
{
    if (is_array($param) || is_object($param)) {
        echo '<pre>';
        print_r($param);
        echo '</pre>';
    } else
        var_dump($param);
    if ($die)
        die();
}

function shortLang($lang)
{
    return substr($lang, 0, 2);
}

function messageOutput($text, $class = 'unocart_red')
{
    return '<span class = "' . $class . '">' . $text . '</span><br />';
}

function parseArrayToParams($array)
{
    $str = '';
    foreach ($array as $key => $value) {
        $str .= $key . "=" . $value . "\n";
    }
    return $str;
}

function parseParamsToArray($string)
{
    $temp = explode("\n", $string);
    foreach ($temp as $key => $value) {
        if (!$value)
            continue;
        $temp2 = explode("=", $value);
        $array[$temp2[0]] = $temp2[1];
    }
    return $array;
}

function smarty_init($folder = "")
{
    global $unocartConfig;
    require_once (JPATH_BASE . '/components/com_unocart/smarty/Smarty.class.php');
    $smarty = new Smarty;
    $unocartConfig->smarty_path = $unocartConfig->path . 'smarty/';

    $smarty->template_dir = $unocartConfig->smarty_path . 'templates/' . $folder;
    $smarty->compile_dir = $unocartConfig->smarty_path . 'templates_c/';
    $smarty->config_dir = $unocartConfig->smarty_path . 'configs/';
    $smarty->cache_dir = $unocartConfig->smarty_path . 'cache/';
    $smarty->register_function("format_price", "format_price");

    $smarty->assign('lang', Jconfig::getInstance()->config_lang);
    return $smarty;
}
/*function smarty_init($folder = "")
{
    global $unocartConfig;
    require_once (JPATH_BASE . '/components/com_unocart/quicky/Quicky.class.php');
    $smarty = new Quicky;
    $smarty->compiler_prefs[`interpritate_varname_params`] = true;    
    $unocartConfig->smarty_path = $unocartConfig->path . 'quicky/';

    $smarty->template_dir = $unocartConfig->smarty_path . 'templates/' . $folder;
    $smarty->compile_dir = $unocartConfig->smarty_path . 'templates_c/';
    $smarty->config_dir = $unocartConfig->smarty_path . 'configs/';
    $smarty->cache_dir = $unocartConfig->smarty_path . 'cache/';
    $smarty->register_function("format_price", "format_price");

    $smarty->assign('lang', Jconfig::getInstance()->config_lang);
    return $smarty;
}*/

function outputDigit($digit, $count_null)
{
    $length = Jstring::strlen(strval($digit));
    for ($i = 0; $i < $count_null - $length; $i++) {
        $digit = '0' . $digit;
    }
    return $digit;
}

function splitValuesArrayObject($array_object, $property_name)
{
    $return = '';
    if (is_array($array_object)) {
        foreach ($array_object as $key => $value) {
            $return .= $array_object[$key]->$property_name . ', ';
        }
        $return = "( " . substr($return, 0, Jstring::strlen($return) - 2) . " )";
    }
    return $return;
}

function replaceArray($search, $replace)
{
    $return = '';
    foreach ($search as $key => $value) {
        $return .= $replace[$key] . "=" . $search[$key] . "\n";
    }
    return $return;
}

// when value not search add to array and sort
function searchValue($value, &$array)
{
    if ($key = array_search($value, $array))
        return $key;
    $array[0] = "0" . $temp = $array[0];
    $array[$value] = $value;
    asort($array);
    $array[0] = $temp;
    return $key - 1;
}

function appendExtendPathWay($array, $page)
{
    global $mainframe, $unocartConfig;
    $count = count($array);
    $i = 0;
    foreach ($array as $cat) {
        if ($count == ++$i && $page == 'categories') {
            $mainframe->appendPathway($cat->category_name);
        } else {
            $mainframe->appendPathway('<a class = "pathway" href = "' . SEFLink('index.php?option=com_unocart&task=categories&category_id=' .
                $cat->category_id) . '">' . $cat->category_name . '</a>');
        }
    }
}

function appendPathWay($page)
{
    global $unocartConfig, $mainframe;
    $mainframe->appendPathWay($page);
}

class parseString
{
    var $string = null;
    var $params = null;
    var $separator = null;
    function parseString($value, $separator = "\n")
    {
        $this->separator = $separator;
        if (is_array($value)) {
            $this->params = $value;
        } else
            if (is_string($value)) {
                $this->string = $value;
            } else {
                return;
            }
    }

    // Rozbyvae, koly typ takyi key1=value1 key2=value2
    function parseStringToParams()
    {
        if (!$this->string)
            return '';
        $params = explode($this->separator, $this->string);
        foreach ($params as $param) {
            $ext_param = explode("=", $param);
            if (!$ext_param[0])
                continue;
            $this->params[Jstring::trim($ext_param[0])] = Jstring::trim($ext_param[1]);
        }
        return $this->params;
    }

    // Robyt split typu key1=value1 key2=value2
    function splitParamsToString()
    {
        $this->string = '';
        foreach ($this->params as $key => $value) {
            $this->string .= Jstring::trim($key) . "=" . Jstring::trim($value) . $this->separator;
        }
        return $this->string;
    }


    // Rozbyvae, koly typ takyi |value1}value2}
    function parseStringToParams2()
    {
        $params = explode($this->separator, $this->string);
        foreach ($params as $param) {
            if (!$param)
                continue;
            $this->params[Jstring::trim($param)] = Jstring::trim($param);
        }
    }

    function getArrayObject($key_name)
    {
        $this->parseStringToParams2();
        $arr_ret = array();
        if (!count($this->params))
            return null;
        foreach ($this->params as $param) {
            $obj->$key_name = $param;
            $arr_ret[] = $obj;
            unset($obj);
        }
        return $arr_ret;
    }

    // Robyt split type |value1|value2}
    function splitParamsToString2()
    {
        $this->string = $this->separator;
        foreach ($this->params as $key => $value) {
            $this->string .= $value . $this->separator;
        }
        return $this->string;
    }
}

function echoHiddenField($array, $row = null)
{
    $output = '';
    foreach ($array as $key => $value) {
        if ($row) {
            $output .= '<input type = "hidden" name = "' . $value . '" value = "' . $row->$value .
                '" />' . "\n";
        } else {
            $output .= '<input type = "hidden" name = "' . $key . '" value = "' . $value .
                '" />' . "\n";
        }
    }
    echo $output;
    return;
}


function format_price($params)
{
    global $unocartConfig, $format_currency;
    $currency_code = (isset($params['currency_code'])) ? ($params['currency_code']) : ($unocartConfig->
        currency_code);
    $params['price'] = number_format($params['price'], $unocartConfig->
        decimal_count, $unocartConfig->decimal_symbol, $unocartConfig->
        thousand_separator);
    $return = Jstring::str_ireplace("Symb", $currency_code, Jstring::str_ireplace("00", $params['price'],
        $format_currency[$unocartConfig->currency_format]));
    return $return;
}

function loadConfig()
{
    $database = &unocartFactory::getDBO();
    $config = new unocartConfig($database);
    $config->load(1);

    $config->path = '/components/com_unocart/';
    $config->admin_path = JPATH_BASE . '/administrator' . $config->path;
    $config->live_path = JPATH_SITE . $config->path;
    $config->live_admin_path = JPATH_SITE . '/administrator' . $config->path;
    $config->path = JPATH_BASE . $config->path;

    $config->image_category_live_path = $config->live_path . $config->
        image_category_path;
    $config->image_category_path = $config->path . $config->image_category_path;

    $config->image_product_live_path = $config->live_path . $config->
        image_product_path;
    $config->image_product_path = $config->path . $config->image_product_path;

    $config->image_manufs_live_path = $config->live_path . $config->
        image_manufs_path;
    $config->image_manufs_path = $config->path . $config->image_manufs_path;

    $config->video_product_live_path = $config->live_path . $config->
        video_product_path;
    $config->video_product_path = $config->path . $config->video_product_path;
    $config->thousand_separator = (!$config->thousand_separator) ? (" ") : ($config->
        thousand_separator);
    $config->files_path = $config->admin_path . "files/";
    $config->other_files_path = $config->path . "other_files/";

    // Special type shop
    if ($config->shop_special_type) {
        $special_types = explode(",", $config->shop_special_type);
        if (is_array($special_types)) {
            $config->shop_special_type = $special_types;
        }
    }
    // End Special type shop

    list($config->pdf_header_width, $config->pdf_header_height, $config->
        pdf_footer_width, $config->pdf_footer_height) = explode(":", $config->
        pdf_parameters);
    $config->pdf_header_width = ($config->pdf_header_width > 208) ? (208) : (intval
        ($config->pdf_header_width));
    $config->pdf_footer_width = ($config->pdf_footer_width > 208) ? (208) : (intval
        ($config->pdf_footer_width));


    // For correct transform html_entity_decode
    $config->charset = 'UTF-8';
    // End charset
    return $config;
}


function getAllLanguages($arr = null)
{
    global $unocartConfig, $mosConfig_absolute_path;

    $rows = array();
    // Read the template dir to find templates
    $languageBaseDir = mosPathName(mosPathName($mosConfig_absolute_path) .
        "language");
    require_once ($mosConfig_absolute_path .
        '/includes/domit/xml_domit_lite_parser.php');
    $rowid = 0;
    $xmlFilesInDir = mosReadDirectory($languageBaseDir, '.xml$');
    $dirName = $languageBaseDir;
    foreach ($xmlFilesInDir as $xmlfile) {
        $xmlDoc = new DOMIT_Lite_Document();
        $xmlDoc->resolveErrors(true);
        if (!$xmlDoc->loadXML($dirName . $xmlfile, false, true)) {
            continue;
        }

        $root = &$xmlDoc->documentElement;

        if ($root->getTagName() != 'mosinstall') {
            continue;
        }
        if ($root->getAttribute("type") != "language") {
            continue;
        }

        $row = new StdClass();
        $row->language = substr($xmlfile, 0, -4);

        $rows[] = $row;
    }

    return $rows;
}

function recurseTree($cat, $level, $all_cats, &$categories, $is_select)
{
    $probil = '';
    if ($is_select) {
        for ($i = 0; $i < 2 * $level; $i++) {
            $probil .= '&nbsp;';
        }
        $cat->category_name = ($probil . $cat->category_name);
        $categories[] = mosHTML::makeOption($cat->category_id, $cat->category_name,
            'category_id', 'category_name');
    } else {
        $cat->level = $level;
        $categories[] = $cat;
    }
    foreach ($all_cats as $categ) {
        if ($categ->category_parent_id == $cat->category_id) {
            recurseTree($categ, ++$level, $all_cats, $categories, $is_select);
            $level--;
        }
    }
    return $categories;
}

function buildTreeCategory($publish = 1, $is_select = 1)
{
    global $database, $unocartConfig;
    $database = &unocartFactory::getDBO();
    $where_add = ($publish) ? (" AND categ.category_publish = '1' ") : ("");
    $query = "SELECT categ.category_id, categ.category_parent_id, categ_descr.category_name, categ.category_publish, categ_descr.category_description
       	      FROM `#__unocart_categories` AS categ
           	  LEFT JOIN `#__unocart_categories_description` AS categ_descr USING (category_id)
           	  WHERE 1 " . $where_add . "
           	  GROUP BY categ.category_id
			  ORDER BY categ.category_parent_id, categ.category_ordering";

    $database->setQuery($query);
    $all_cats = $database->loadObjectList();

    $query = "SELECT *
	          FROM `#__unocart_categories_description` AS categ_descr
	          LEFT JOIN `#__unocart_categories` AS categ ON categ.category_id = categ_descr.category_id
			  ORDER BY categ.category_id, categ_descr.language";
    $database->setQuery($query);
    $categ_descr = $database->loadObjectList();
    $cats_descr = array();
    foreach ($categ_descr as $categ) {
        $cats_descr[$categ->category_id][$categ->language] = $categ;
    }

    foreach ($cats_descr as $key => $value) {
        if (isset($value[$unocartConfig->cur_lang])) {
            foreach ($all_cats as $key2 => $value2) {
                if ($value2->category_id == $key) {
                    $all_cats[$key2]->category_name = $value[$unocartConfig->cur_lang]->
                        category_name;
                    break;
                }

            }
        } else {
            foreach ($all_cats as $key2 => $value2) {
                if ($value2->category_id == $key) {
                    $all_cats[$key2]->category_name = $value2->category_name;
                    break;
                }
            }
        }
    }

    if (count($all_cats)) {
        foreach ($all_cats as $key2 => $value2) {
            if (!$value2->category_parent_id)
                recurseTree($value2, 0, $all_cats, $categories, $is_select);
        }
    } else {
        $categories = array();
    }
    return $categories;
}

function includeCalendar()
{
    global $my;
    if (!$my->id) {
        global $mainframe;
        $mainframe->addCustomHeadTag('<script type = "text/javascript" src = "' .
            JPATH_SITE . '/includes/js/joomla.javascript.js"></script>');
    }
    mosCommonHTML::loadOverlib();
    mosCommonHTML::loadCalendar();
}

function checkMyDate($date)
{
    if (!Jstring::trim($date))
        return true;
    // Format date y-mm-dd
    $arr = explode("-", $date);
    return checkdate($arr[0], $arr[1], $arr[2]);
}

function recursiveHtmlSpecialChars(&$value)
{
    return is_array($value) ? array_map('recursiveHtmlSpecialChars', $value) :
        htmlspecialchars(stripslashes($value), ENT_QUOTES);
}

?>